<template>
    <div class="operation-map">
        <!-- 头部标题栏 -->
        <div class="header">
            <div class="time">{{ currentYear }}财年 {{ currentDate }}</div>
            <div class="title">作战指挥中心</div>
            <div class="header-right">
                <div class="button-group">
                    <el-radio-group v-model="selectedArea" size="small" text-color="#CE2827" fill="#ffffff"
                        class="custom-radio" @change="selectedAreaChange">
                        <el-radio-button label="行政区">行政区</el-radio-button>
                        <el-radio-button label="组织">组织</el-radio-button>
                    </el-radio-group>
                    <el-select v-model="selectedAll" size="small" class="all-select" placeholder="全部品牌"
                        @change="selectedAllChange">
                        <el-option v-for="item in allOptions" :key="item.value" :label="item.label" :value="item.value">
                            <span class="select-label">{{ item.label }}</span>
                        </el-option>
                    </el-select>
                </div>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content">
            <div class="charts-container">
                <!-- 左侧图表 -->
                <div class="left-charts" v-if="!lookSaveType">
                    <div v-for="(chart, index) in leftCharts" :key="index" class="chart-item"
                        @click="handleChartClick(chart.type, 'left', index)">
                        <bi-line-chart :title="chart.title" :chart-data="chart.data" :options="chart.options"
                            :resize="resize" @Change="LeftChange($event, 'left', index)" @dataZoom="dataZoom"
                            ref="biLineChartFn" :day.sync="chart.day" @update:day="newDay => chart.day = newDay" />
                    </div>
                </div>
                <!-- 右侧图表 -->
                <div class="right-charts" v-if="!lookSaveType">
                    <div v-for="(chart, index) in rightCharts" :key="index" class="chart-item"
                        @click="handleChartClick(chart.type, 'right', index)">
                        <bi-line-chart :title="chart.title" :chart-data="chart.data" :options="chart.options"
                            :resize="resize" @Change="LeftChange($event, 'right', index)" @dataZoom="dataZoom"
                            ref="biLineChartFn" :day.sync="chart.day" @update:day="newDay => chart.day = newDay" />
                    </div>
                </div>
                <!-- 点击库存金额的图表 -->
                <div class="left-charts" v-if="lookSaveType">
                    <div class="chart-item" v-for="(chart, index) in SaveLeftCharts" :key="index"
                        @click="handleChartClick(chart.type)">
                        <bi-line-chart v-if="chart.type1 === 'line'" :title="chart.title" :chart-data="chart.data"
                            :options="chart.options" @Change="LeftChange($event, 'line', index)" @dataZoom="dataZoom"
                            ref="biLineChartFn" :day.sync="chart.day" @update:day="newDay => chart.day = newDay" />
                        <bi-bar-chart v-else :title="chart.title" :chart-data="chart.data" :options="chart.options"
                            @Change="LeftChange($event, 'bar', index)" @dataZoom="dataZoom" ref="biBarChartFn" />
                    </div>
                </div>
            </div>
            <!-- 数据展示 -->
            <div class="map-overview">
                <div class="overview-item" v-for="(item, index) in mapOverviewData" :key="index" @click="lookSave(item)"
                    :style="{
                        padding: `14px ${setPaddingLeftRight(index)} 17px`,
                        minWidth: `${index === 0 ? 160 : 120}px`
                    }" :class="{
                        FnSetBgc: lookSaveType && item.label.includes('库存金额')
                    }">
                    <div class="value-container" :class="{
                        FnSetColor: lookSaveType && item.label.includes('库存金额')
                    }">
                        <span class="value">{{ item.value }}</span>
                        <span class="unit" v-if="item.unit">{{ item.unit }}</span>
                        <span class="percent" v-if="item.percent">{{ item.percent }}</span>
                    </div>
                    <div class="label" :class="{
                        FnSetColor: lookSaveType && item.label.includes('库存金额')
                    }">{{ item.label }}</div>
                </div>
            </div>
            <!-- 中间地图 -->
            <div class="map-container" v-if="selectedArea === '行政区'">
                <!-- 地图组件将在这里添加 -->
                <div class="map-wrapper">
                    <!-- <bi-china-map /> -->
                    <ChartsMap @map-click="(e) => handleMapClick(e)" @marker-click="markerClick"
                        @handleBack="handleBack"></ChartsMap>
                </div>
            </div>
            <!-- 组织部分 -->
            <div class="organization" v-if="selectedArea === '组织'">
                <div class="organization_title">
                    <div class="organization_title_radio" style="">
                        <el-radio-group v-model="organizationRadio" size="medium " fill="#EA1111"
                            @change="organizationRadioChange">
                            <el-radio-button label="省内" />
                            <el-radio-button label="省外" />
                        </el-radio-group>
                    </div>
                    <div class="organization_title_right">
                        <div class="organization_title_right_back" v-if="clickDown" @click="gotoBack">
                            <div>上一级</div>
                            <div><i class="el-icon-fanhuishangyiji" style="color: #666;" /></div>
                        </div>
                        <div class="organization_title_right_all">
                            <el-select v-model="organizationSelect" placeholder="请选择" size="small" @change="showSelect">
                                <el-option v-for="item in SelectOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>

                        </div>
                    </div>
                </div>
                <div class="organization_content" ref="parent" v-loading="elLoading">
                    <template v-for="item, index in organizationContent">
                        <div :key="index" class="organization_content_item" ref="child" :style="{
                            width: setOrganizationContentWidth(item.number, item.color) + 'px',
                            height: '94px',
                            background: setOrganizationContentBgc(item.color)
                        }" @mouseenter="showPopover(index, item)" @mouseleave="hidePopover" @click="gotoCity(item)">
                            <div class="organization_content_item_top">
                                <div style="text-align: center;">{{ item.name }}</div>
                                <div class="organization_content_item_top_right">
                                    <div><i :class="item.up ? 'el-icon-top' : 'el-icon-bottom'" style="color: #fff;" />
                                    </div>
                                    <div>{{ item.rise }}</div>
                                </div>
                            </div>
                            <div v-if="item.number > 0">{{ `(${setOrganizationContentNumber(item.number)})` }}</div>
                            <div v-if="hoveredIndex === index" class="hovered" :style="{
                                left: leftValue + 'px',
                                top: TopValue + 'px'
                            }">
                                <div class="hovered_title">{{ item.name }}</div>
                                <div class="hovered_item">
                                    <div v-for="value, valueIndex in item.amount" :key="valueIndex"
                                        class="hovered_item_for">
                                        <div>{{ value.name }}</div>
                                        <div>{{ value.money }}</div>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </template>
                </div>
                <div class="organization_bottom">
                    <div class="organization_bottom_title">经销商完成情况热力示意</div>
                    <div v-for="item, index in textList" :key="index" class="organization_bottom_item">
                        <div :style="{
                            width: '14px',
                            height: '14px',
                            background: item.bgc
                        }"></div>
                        <div style="margin-top: 2px;">{{ item.text }}</div>
                    </div>
                </div>
            </div>
            <div v-if="!lookSaveType">
                <div v-if="cityLevel !== 'area'" class="tableData">
                    <el-table :data="tableData" style="width: 100%;table-layout:fixed" border
                        :header-cell-style="{ 'text-align': 'center', 'background': '#FFF3F3' }">
                        <el-table-column label="经销商等级">
                            <template slot-scope="scope">
                                <span class="table-cell">{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-for="(amount, index) in amountColumns" :key="index" :label="amount.label">
                            <template slot-scope="scope">
                                <div class="amount-cell">
                                    <div style="display: flex;justify-content: center;align-items: center;">
                                        <div class="amount-cell_left">{{ scope.row[amount.key].number }}</div>
                                        <div class="amount-cell_right">
                                            <div>
                                                <i :class="scope.row[amount.key].up ? 'el-icon-top' : 'el-icon-bottom'"
                                                    :style="{
                                                        color: scope.row[amount.key].up ? '#E65C6B' : '#70B777'
                                                    }" />
                                            </div>
                                            <div :style="{
                                                color: scope.row[amount.key].up ? '#E65C6B' : '#70B777'
                                            }">
                                                {{ scope.row[amount.key].rise }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div v-else>
                    <div class="iconBox">
                        <div>
                            <div style="display: flex;align-items: center;justify-content: center;">
                                <img src="../../image/top.png" alt="" style="width: 20px;height: 23px;">
                            </div>
                            <div>经销商</div>
                        </div>
                        <div>
                            <div>
                                <img src="../../image/bottom.png" alt="" style="width: 20px;height: 23px;">
                            </div>
                            <div>终端</div>
                        </div>
                    </div>
                    <div class="tableData" v-if="markerObj">
                        <div class="mark_tab">
                            <div class="mark_tab_left">
                                <div class="mark_tab_left_shop" v-if="false">
                                    <img src="../../image/test.png" alt=""
                                        style="width: 144px;height: 88px;border-radius: 4px;">
                                </div>
                                <div class="mark_tab_right">
                                    <div class="mark_tab_right_img">
                                        <img src="../../image/dianpu.png" alt="" srcset=""
                                            style="width: 22px;height: 22px;">
                                    </div>
                                    <div class="mark_tab_right_details">
                                        <div class="mark_tab_right_details_top">
                                            <div>{{ markerObj.mainCustomerName }}</div>
                                            <div style="color:#999999">{{ markerObj.mainCustomerCode }}</div>
                                        </div>
                                        <div class="mark_tab_right_details_text">
                                            <div style="display: flex;column-gap: 22px;">
                                                <div style="color:#C5C5C5">合作品牌：</div>
                                                <div>{{ markerObj.brandName }}</div>
                                            </div>
                                            <div style="display: flex;column-gap: 10px;">
                                                <div style="color:#C5C5C5">消费者开瓶：</div>
                                                <div style="display: flex;align-items: end;">
                                                    <div style="color: #BB2B24;">{{ markerObj.openCnt }}</div>
                                                    <div style="font-size: 10px;">瓶</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="warningList" v-if="false">
                                <div style="width: 20px;height: 20px;">
                                    <img src="../../image/warning.png" style="width: 100%;height: 100%;">
                                </div>
                                <div style="padding: 0 3px 0 5px;">终端异地开瓶率高于35%</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 详情弹窗 -->
            <bi-chart-detail-dialog :visible="dialogVisible" :title="dialogTitle"
                :line-chart-title="dialogLineChartTitle" :line-chart-data="dialogLineChartData"
                :line-chart-options="dialogLineChartOptions" :bar-chart-title="dialogBarChartTitle"
                :bar-chart-data="dialogBarChartData" :bar-chart-options="dialogBarChartOptions"
                @dialogSelectedStepChange="dialogSelectedStepChange" @update:visible="val => dialogVisible = val"
                @close="handleDialogClose" :detail-dialog-name-list="detailDialogNameList" :color-list="colorList"
                @handleBarClick="lineCharthandleBarClick" @handleBack="lineCharthandleBack" :chartType="diaLogChatrType"
                @dialogDataZoom="dataZoom" />
        </div>
    </div>
</template>

<script>
import { Message } from 'element-ui'
import BiLineChart from './components/LineChart.vue'
import BiBarChart from './components/BarChart.vue'
import ChartsMap from './components/chartsmap.vue'
import BiChartDetailDialog from './components/ChartDetailDialog.vue'
import { getRegion, getRegionMap, getSalesLineChartData, login } from '@/api/user'
export default {
    name: 'OperationMap',
    components: {
        BiLineChart,
        BiChartDetailDialog,
        ChartsMap,
        BiBarChart
    },
    inject: ['reload'],
    data() {
        return {
            resize: null,
            brandType: 'series',
            isBrowserFullScreen: false,
            lookSaveType: false,
            organizationSelect: "销售目标",
            clickDown: false,
            leftValue: "-50",
            TopValue: "70",
            FullYear: `${new Date().getFullYear()}`,
            detailDialogNameList: [],
            colorList: ['#04BA6F', '#EA1111', '#F9C54B'],
            textList: [
                {
                    text: "好",
                    bgc: "#E65C6B"
                },
                {
                    text: "正常",
                    bgc: "#F9C54B"
                }, {
                    text: "差",
                    bgc: "#70B777"
                }],
            currentYear: '2025',
            currentDate: '',
            // 下拉选择数据
            selectedArea: '行政区',
            selectedAll: '',
            allOptions: [
                { label: '全部品牌', value: '' },
                { label: '国缘', value: '国缘' },
                { label: '国缘V系', value: '国缘V系' },
                { label: '今世缘', value: '今世缘' },
            ],
            SaveLeftCharts: [
                {
                    type: 'terminal',
                    type1: 'line',
                    day: "月",
                    title: '经销商进销存',
                    // chartTitle: ['出货金额', '库存金额', '进货金额'],
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "元"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['终端数量']
                        }
                    }
                },

                {
                    type: 'salesbar',
                    type1: 'bar',
                    title: '区域库销比',
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "元"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['终端数量']
                        }
                    }
                }
            ],
            // 左侧图表配置
            leftCharts: [
                {
                    type: 'sales',
                    title: '销售目标及完成',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "元"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['销售目标', '销售完成']
                        }
                    }
                },
                {
                    type: 'inventory',
                    title: '经销库存及出货',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "元"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['出货', '库存']
                        }
                    }
                },
                {
                    type: 'compare',
                    title: '终端进货/消费者开瓶对比',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "瓶"
                            }
                        ]
                    },

                    options: {
                        legend: {
                            data: ['终端进货', '消费者开瓶']
                        }
                    }
                }
            ],
            // 右侧图表配置
            rightCharts: [
                {
                    type: 'expense',
                    title: '费用投入情况',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "元"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['费用投入金额', '销售完成金额']
                        }
                    }
                },
                {
                    type: 'terminal',
                    title: '终端宴席',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "次"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['终端数量']
                        }
                    }
                },
                {
                    type: 'scan',
                    title: '开瓶扫码',
                    day: "月",
                    data: {
                        xAxis: [],
                        series: [

                        ],
                        yAxis: [
                            {
                                type: "value",
                                unit: "瓶"
                            }
                        ]
                    },
                    options: {
                        legend: {
                            data: ['扫码数量']
                        }
                    }
                }
            ],
            // 地图概览数据
            mapOverviewData: [
                {
                    value: '600,000',
                    unit: '万元',
                    label: '销售完成',
                    percent: '60%'
                },
                {
                    value: '400,000',
                    label: '库存金额(万元)'
                },
                {
                    value: '10,000',
                    label: '费用投入金额(万元)'
                },
                {
                    value: '4,000',
                    label: '开瓶数(万瓶)'
                }
            ],
            // 地图数据
            mapData: [
                { name: '北京', value: 98 },
                { name: '天津', value: 85 },
                { name: '河北', value: 76 },
                // ... 其他省份数据
            ],
            // 弹窗相关数据
            dialogVisible: false,
            dialogTitle: '',
            dialogLineChartTitle: '',
            dialogLineChartData: {
                xAxis: [],
                series: []
            },
            dialogLineChartOptions: {},
            dialogBarChartTitle: '',
            dialogBarChartData: {
                xAxis: [],
                series: []
            },
            dialogBarChartOptions: {},
            organizationRadio: "省内",
            organizationContent: [],
            arrData: [],
            tableData: [
                {
                    name: "经销商数量",
                    amount1: { number: 500, up: true, rise: 4 },
                    amount2: { number: 300, up: false, rise: 4 },
                    amount3: { number: 100, up: true, rise: 1 },
                    amount4: { number: 500, up: false, rise: 2 },
                    amount5: { number: 13, up: false, rise: 1 },
                },
            ],
            amountColumns: [
                { label: "1000万以下", key: "amount1" },
                { label: "1000~5000万", key: "amount2" },
                { label: "5000万~1亿", key: "amount3" },
                { label: "1亿~2亿", key: "amount4" },
                { label: "2亿以上", key: "amount5" },
            ],
            SelectOptions: [
                { label: '销售目标', value: '销售目标' },
                { label: '销售完成', value: '销售完成' },
                { label: '经销商出货', value: '经销商出货' },
                { label: '终端进货', value: '终端进货' },
                { label: '费用投入', value: '费用投入' },
                { label: '开瓶扫码', value: '开瓶扫码' },
                { label: '异地扫码', value: '异地扫码' }
            ],
            hoveredIndex: null,
            day: {
                "周": "weeks",
                "月": "month",
                "日": "day"
            },
            enumObj: {
                "销售目标及完成": "getSalesLineChartData",
                "经销库存及出货": "getCustomerStockLineChartData",
                "终端进货/消费者开瓶对比": "getTerminalConsumerOpenLineChartData",
                "费用投入情况": "getCostInputLineChartData",
                "终端宴席": "getTerminalBanquetLineChartData",
                "开瓶扫码": "getCustomerOpenBottleLineChartData",
                "经销商进销存": "getCustomerPurchaseSalesLineChartData",
                "区域库销比": "getRegionInventorySalesBarChartData"
            },
            SN: "SN",
            cityName: undefined,
            cityLevel: 'country',
            newOrgType: undefined,
            newOrgName: undefined,
            copyRegionVos: [],
            copyRegionShowVos: [],
            copyCustomerScaleVos: [],
            copyHeaderVo: [],
            elLoading: true,
            regionName: null,
            markerObj: undefined,
            redColorArr: [],
            yellowColorArr: [],
            greenColorArr: [],
            copyChickCityTopData: [],
            copyChickCityBottomData: [],
            diaLogChatrType: "double",
            dialogDirection: null,
            dialogIndex: 0,
            timerId: null
        }
    },
    computed: {
        setPaddingLeftRight() {
            return function (index) {
                let padding = "13px"
                // if(index > 0) padding = '33px'
                return padding
            }
        },
        // 根据arrData生成盒子的宽度
        setOrganizationContentWidth() {
            return function (value, color, _maxWidth, _minWidth,) {
                let maxWidth, minWidth, arr
                switch (color) {
                    case '红色':
                        maxWidth = 330;  // 红色的最大宽度
                        minWidth = 230;  // 红色的最小宽度
                        arr = this.redColorArr
                        break;
                    case '黄色':
                        maxWidth = 200;  // 黄色的最大宽度
                        minWidth = 160;  // 黄色的最小宽度
                        arr = this.yellowColorArr
                        break;
                    case '绿色':
                        maxWidth = 150;  // 绿色的最大宽度
                        minWidth = 146;  // 绿色的最小宽度
                        arr = this.greenColorArr
                        break;
                    default:
                        maxWidth = _maxWidth ?? 330;  // 默认最大宽度
                        minWidth = _minWidth ?? 126;   // 默认最小宽度
                        arr = []
                        break;
                }
                const maxValue = Math.max(...arr); // 获取最大值
                const minValue = Math.min(...arr); // 获取最小值
                const range = maxValue - minValue;
                const widthPercentage = ((value - minValue) / (range || 1));
                return Math.min(Math.max(widthPercentage * maxWidth, minWidth), maxWidth);
            }
        },
        // 组织的盒子背景颜色渲染
        setOrganizationContentBgc() {
            return function (value) {
                const colorObj = {
                    '红色': '#E65C6B',
                    '黄色': '#F9C54B',
                    '绿色': '#70B777'
                }
                return colorObj[value] ?? '#70B777'
            }
        },
        setOrganizationContentNumber() {
            return function (value, type) {
                let formattedValue;
                if (value < 10000) {
                    formattedValue = value.toFixed(2).replace(/\.00$/, '').replace(/\.0$/, '').replace(/\.([1-9])0$/, '.\$1') + (this.organizationSelect.includes("扫") ? '瓶' : "元");
                } else if (value < 100000000) {
                    formattedValue = (value / 10000).toFixed(2).replace(/\.00$/, '').replace(/\.0$/, '').replace(/\.([1-9])0$/, '.\$1') + (this.organizationSelect.includes("扫") ? '万瓶' : "万元");
                } else {
                    formattedValue = (value / 100000000).toFixed(2).replace(/\.00$/, '').replace(/\.0$/, '').replace(/\.([1-9])0$/, '.\$1') + (this.organizationSelect.includes("扫") ? '亿瓶' : "亿元");
                }

                return formattedValue
            };
        }
    },
    created() {

    },
    mounted() {
        this.timerId = setInterval(() => {
            this.currentDate = this.formatDate(new Date())
        }, 1000)

        window.addEventListener('resize', this.checkFullScreen)
        this.initialize()
        this.initChinaMap()

    },
    beforeDestroy() {
        clearInterval(this.timerId);
        window.removeEventListener('resize', this.checkFullScreen)
        if (this.chinaMap) {
            this.chinaMap.dispose()
            this.chinaMap = null
        }
    },
    methods: {
        checkFullScreen() {
            // 判断当前是否为浏览器全屏模式[1,4](@ref)
            this.isBrowserFullScreen = window.outerHeight === screen.availHeight
        },
        initialize() {
            this.fetchAllData()
            this.getTabTopData()
            this.getTabBottomData()
        },
        lineCharthandleBarClick(event) {
            const { name, currentLevel } = event
            this.getDialogLineData(undefined, currentLevel, name)
        },
        lineCharthandleBack(event) {
            const { currentLeve, name } = event
            console.log(event);

            const currentLevelObj = {
                0: 'brand',
                1: 'series',
                2: 'product_level'
            }
            this.getDialogLineData(undefined, currentLevelObj[currentLeve], currentLeve > 0 ? name[currentLeve - 1] : this.selectedAll)
        },
        // 获取左右图表的数据
        getData(url = 'getSalesLineChartData', dateType = 'month', dateStr, brandType, mainCustomerCode, dateList, monthWeek) {
            getSalesLineChartData(url, dateType, this.cityLevel, this.cityName === '中国' ? undefined : this.cityName, this.newOrgType, this.newOrgName || '', brandType, this.selectedAll, this.markerObj?.mainCustomerCode || '', dateList, monthWeek, dateStr, this.selectedArea === '行政区' ? undefined : this.SN).then(res => {
                const { data } = res;
                // 根据 URL 更新相应的图表数据        
                this.updateChartData(url, data);
            }).catch(error => {
                console.error(`获取数据失败: ${error}`);
            });
        },
        // 获取头部表格数据
        getTabTopData() {
            getRegionMap(undefined, this.FullYear, this.cityLevel, this.cityName === '中国' ? undefined : this.cityName, undefined, undefined, undefined, this.selectedAll).then(res => {
                this.currentYear = res.data.yearNo
                this.updataTabTopData(res.data)
            })
        },
        upOrganizationArrayData(customerScaleVos, headerVo, regionShowVos, name) {
            this.updataTabBottomData(customerScaleVos)
            this.updataTabTopData(headerVo)
            const colorWeight = {
                '红色': 1,
                '黄色': 2,
                '绿色': 3
            };
            this.redColorArr = []
            this.yellowColorArr = []
            this.greenColorArr = []
            const organizationSelectMap = {
                '销售目标': 'contractAmt',
                '销售完成': 'salesAmt',
                '经销商出货': 'outboundAmt',
                '终端进货': 'terminalSignAmt',
                '费用投入': 'costAmt',
                '开瓶扫码': 'openCnt',
                '异地扫码': 'notNormalOpenCnt'
            };
            const selectedKey = organizationSelectMap[this.organizationSelect];
            const nowData = regionShowVos.map(item => {
                if (item.color === '红色') this.redColorArr.push(item[selectedKey])
                if (item.color === '黄色') this.yellowColorArr.push(item[selectedKey])
                if (item.color === '绿色') this.greenColorArr.push(item[selectedKey])
                return {
                    ...item,
                    up: item.rankChange > 0,
                    rise: Math.abs(item.rankChange),
                    name: item[name],
                    color: item.color ?? '绿色',
                    number: item[selectedKey],
                    amount: this.createAmountData(item)
                };
            }).filter(item => item !== undefined);
            nowData.sort((a, b) => {
                const colorComparison = colorWeight[a.color] - colorWeight[b.color];
                if (colorComparison !== 0) {
                    return colorComparison;
                }
                return b.number - a.number;
            });
            this.elLoading = false
            return nowData
        },
        updataTabTopData(data) {
            //  openCnt 开瓶瓶数
            // costAmt 费用投入金额
            // stockAmt 库存金额
            // completeRate 完成率
            // percentag 百分比
            // salesAmt 销售金额
            const { openCnt, costAmt, stockAmt, completeRate, salesAmt, percentage } = data
            // 防止Vue响应式数据丢失
            const Rate = completeRate ?? percentage ?? 0
            this.$set(this.mapOverviewData[0], 'value', this.setYuanUnit(salesAmt)[0]);
            this.$set(this.mapOverviewData[0], 'unit', this.setYuanUnit(salesAmt)[1]);
            this.$set(this.mapOverviewData[0], 'percent', `${Rate.toFixed(1)}%`);
            this.$set(this.mapOverviewData[1], 'value', stockAmt < 0 ? `-${this.setYuanUnit(Math.abs(stockAmt))[0]}` : this.setYuanUnit(stockAmt)[0]);
            this.$set(this.mapOverviewData[1], 'label', `库存金额(${this.setYuanUnit(Math.abs(stockAmt))[1]})`);
            this.$set(this.mapOverviewData[2], 'value', this.setYuanUnit(costAmt)[0]);
            this.$set(this.mapOverviewData[2], 'label', `费用投入金额(${this.setYuanUnit(costAmt)[1]})`);
            this.$set(this.mapOverviewData[3], 'value', this.setYuanUnit(openCnt)[0]);
            this.$set(this.mapOverviewData[3], 'label', `开瓶数(${this.setYuanUnit(openCnt, true)[1]})`);
        },
        // 获取底部表格数据
        getTabBottomData() {
            getRegionMap("getRegionMapScaleLevelCnt", this.FullYear, this.cityLevel, this.cityName === '中国' ? undefined : this.cityName, undefined, undefined, undefined, this.selectedAll).then(res => {
                this.updataTabBottomData(res.data)
            })
        },
        updataTabBottomData(data) {
            const obj = {
                '1000万以下': 'amount1',
                '1000~5000万': 'amount2',
                '5000万~1亿': 'amount3',
                '1亿~2亿': 'amount4',
                '2亿以上': 'amount5'
            }
            this.tableData = [
                {
                    name: "经销商数量",
                    amount1: { number: 0, up: false, rise: 0 },
                    amount2: { number: 0, up: false, rise: 0 },
                    amount3: { number: 0, up: false, rise: 0 },
                    amount4: { number: 0, up: false, rise: 0 },
                    amount5: { number: 0, up: false, rise: 0 },
                }
            ]
            data.forEach(item => {
                const key = obj[item.scaleLevelDesc] ?? obj[item.levelTag]

                if (key) {
                    this.tableData[0][key].number = item.customerCnt ?? item.levelCustomerCount
                    this.tableData[0][key].up = (item.customerCntIncrease ?? item.levelCountChange) > 0
                    this.tableData[0][key].rise = Math.abs(item.customerCntIncrease ?? item.levelCountChange)
                }
            })
        },
        // 格式化数据
        setYuanUnit(value, type) {
            if (value < 10000) {
                return [value?.toFixed(1) ?? 0, (type ? '瓶' : '元')];
            } else if (value < 100000000) {
                return [(value / 10000)?.toFixed(1) ?? 0, (type ? '万瓶' : '万元')]
            } else {
                return [(value / 100000000)?.toFixed(1) ?? 0, (type ? '亿瓶' : '亿元')];
            }
        },
        // 更新对应图表
        updateChartData(url, data) {
            let chartIndex;
            switch (url) {
                case 'getSalesLineChartData':
                    chartIndex = 0;
                    break;
                case 'getCustomerStockLineChartData':
                    chartIndex = 1;
                    break;
                case 'getCostInputLineChartData':
                    chartIndex = 0;
                    this.rightCharts = this?.rightCharts ?? [];
                    break;
                case 'getTerminalConsumerOpenLineChartData':
                    chartIndex = 2;
                    break;
                case 'getCustomerOpenBottleLineChartData':
                    chartIndex = 2;
                    this.rightCharts = this?.rightCharts ?? [];
                    break;
                case 'getTerminalBanquetLineChartData':
                    chartIndex = 1;
                    this.rightCharts = this?.rightCharts ?? [];
                    break;
                case 'getCustomerPurchaseSalesLineChartData':
                    chartIndex = 0;
                    break
                case 'getRegionInventorySalesBarChartData':
                    chartIndex = 1;
                    break
                default:
                    return;
            }
            const targetChart = this.lookSaveType ? this.SaveLeftCharts[chartIndex] : url.startsWith('getCostInput') || url.startsWith('getCustomerOpenBottle') || url.startsWith('getTerminalBanquet') ? this.rightCharts[chartIndex] : this.leftCharts[chartIndex];
            if (targetChart) {
                const chartData = targetChart.data;
                const { xdata = [], series = [], dateStr = '' } = data;

                if (Array.isArray(xdata)) {
                    chartData.xAxis = [...xdata, ...chartData.xAxis];
                }

                chartData.dateStr = dateStr;
                chartData.color = this.colorList
                if ((!series || !Array.isArray(series)) && !this.dialogVisible) {
                    return targetChart.data.xAxis = [...targetChart.data.xAxis];
                }
                if (url.startsWith('getRegionInventorySalesBarChartData')) {
                    chartData.series = [...series, ...chartData.series];
                } else {
                    chartData.legend = {
                        itemWidth: 20,
                        itemHeight: 12,
                        selectedMode: false,
                        icon: "roundRect",
                        type: 'scroll',
                        orient: 'horizontal',//水平排列(默认)
                        width: '70%',
                        top: '-2%',
                        right: '13%',
                        x: 'right',      //可设定图例在左、右、居中
                        y: 'top',
                        pagelconColor: '#333',
                        borderRadius: 20,
                        pageTextStyle: {
                            color: '#666'// 页码文字颜色
                        },
                    }
                    series?.forEach((seriesData, index) => {
                        if (!chartData.series[index]) {
                            chartData.series[index] = {
                                data: [],
                                name: '',
                                itemStyle: {}
                            };
                        }
                        chartData.series[index].data = [...(seriesData.data ?? []), ...chartData.series[index].data];
                        chartData.series[index].name = seriesData.name;
                        chartData.series[index].itemStyle = {
                            normal: {
                                label: {
                                    show: true, // 显示拐点数据
                                    color: this.colorList[index]
                                },
                                color: this.colorList[index] // 拐点边框颜色
                            }
                        };
                    });
                }
                if (this.dialogVisible) {
                    if (!series || !Array.isArray(series)) {
                        return this.processChartData(targetChart)
                    }
                    this.handleChartClick(targetChart.type, (url.startsWith('getCostInput') || url.startsWith('getCustomerOpenBottle') || url.startsWith('getTerminalBanquet') ? 'right' : 'left'), chartIndex)
                }
            }

        },
        formatDate(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hours = String(date.getHours()).padStart(2, '0')
            const minutes = String(date.getMinutes()).padStart(2, '0')
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        },
        fetchAllData(brandType, mainCustomerCode, dateList, monthWeek) {
            const requests = [
                'getSalesLineChartData',
                'getCustomerStockLineChartData',
                'getCostInputLineChartData',
                'getTerminalConsumerOpenLineChartData',
                'getCustomerOpenBottleLineChartData',
                'getTerminalBanquetLineChartData'
            ];
            Promise.allSettled(requests.map(url => this.getData(url, 'month', brandType, mainCustomerCode, dateList, monthWeek))).then(res => {
                console.log("所有接口获取成功");
            })
        },
        initChinaMap() {
            // this.chinaMap = echarts.init(this.$refs.chinaMap)
            // 配置中国地图
        },
        handleAreaChange({ code, name, level }) {
            // 处理地图区域切换事件
            console.log('当前区域:', name, '层级:', level)
            // 这里可以根据区域变化更新其他图表数据
        },
        processChartData(chartData) {
            this.dialogLineChartTitle = chartData.title;
            this.dialogLineChartData = chartData.data;
            this.dialogLineChartData.day = chartData.day;
            this.dialogLineChartData.legend = {
                icon: "roundRect",
                type: 'scroll',
                orient: 'horizontal',
                width: '70%',
                top: '0%',
                right: '13%',
                x: 'right',
                y: 'top',
                pagelconColor: '#333',
                pageTextStyle: {
                    color: '#666'
                },
            };
        },
        handleChartClick(type, direction, index, day = 'month') {
            const result = this.lookSaveType ? this.areAllSeriesDataPresent(this.SaveLeftCharts) : this.areAllSeriesDataPresent(this.leftCharts, this.rightCharts)
            if (result) {
                this.dialogLineChartData = {};
                localStorage.setItem('data', JSON.stringify({
                    cityLevel: this.cityLevel,
                    cityName: this.cityName,
                    newOrgType: this.newOrgType,
                    newOrgName: this.newOrgName,
                    selectedAll: this.selectedAll,
                }));
                this.dialogDirection = direction
                this.dialogIndex = index

                if (type === 'sales') {
                    this.diaLogChatrType = "double";
                    this.dialogTitle = '销售目标详情';
                    this.dialogLineChartTitle = '品牌销售完成金额';
                    this.detailDialogNameList = [];
                    this.getDialogLineData();
                    this.getDialogBarData();
                    this.dialogBarChartTitle = '品牌销售排名';
                } else if (type === 'salesbar') {
                    const salesBarData = this.SaveLeftCharts[1];
                    this.diaLogChatrType = "bar";
                    this.dialogBarChartTitle = salesBarData.title;
                    this.dialogBarChartData = salesBarData.data;
                } else {
                    this.diaLogChatrType = "line";
                    let nowData;
                    if (this.lookSaveType) {
                        nowData = JSON.parse(JSON.stringify(this.SaveLeftCharts[0]));
                    } else {
                        nowData = direction === 'left'
                            ? JSON.parse(JSON.stringify(this.leftCharts[index]))
                            : JSON.parse(JSON.stringify(this.rightCharts[index]));
                    }
                    this.processChartData(nowData);
                }
                this.dialogVisible = true;
            }
        },
        dialogSelectedStepChange(event) {
            const { day, enumObj, dialogDirection, dialogIndex } = this
            const { title, selectedStep } = event
            if (this.lookSaveType) {
                this.SaveLeftCharts[0].day = selectedStep
                this.clearChartData(this.SaveLeftCharts[0])
            } else {
                if (dialogDirection === 'left') {
                    this.leftCharts[dialogIndex].day = selectedStep
                    this.clearChartData(this.leftCharts[dialogIndex])
                }
                else {
                    this.rightCharts[dialogIndex].day = selectedStep
                    this.clearChartData(this.rightCharts[dialogIndex])

                }
            }
            this.getData(enumObj[title], day[selectedStep])
            // this.getDialogLineData(day[selectedStep])
            // this.getDialogBarData(day[selectedStep])
        },
        getDialogBarData(day = 'month') {
            getSalesLineChartData('getSalesBrandBarChartData', day, this.cityLevel, this.cityName, this.newOrgType, this.newOrgName, 'brand', this.selectedAll).then(res => {
                const { data } = res;
                this.$set(this.dialogBarChartData, 'xAxis', data.xdata)
                this.$set(this.dialogBarChartData, 'series', data.series)
            }).catch(error => {
                console.error(`获取数据失败: ${error}`);
            });
        },
        getDialogLineData(day = "month", brand = 'brand', name) {
            getSalesLineChartData('getSalesBrandLineChartData', day, this.cityLevel, this.cityName, this.newOrgType, this.newOrgName, brand, name ?? this.selectedAll).then(res => {
                const { data } = res;
                // let arr = []
                // data.series.map((item, index) => {
                //     return arr.push({
                //         name: item.name,
                //     })
                // }),
                this.dialogLineChartData = {
                    color: this.colorList,
                    xAxis: data.xdata,
                    legend: {
                        icon: "roundRect",
                        type: 'scroll',
                        orient: 'horizontal',//水平排列(默认)
                        width: '70%',
                        top: '-2%',
                        right: '13%',
                        x: 'right',      //可设定图例在左、右、居中
                        y: 'top',
                        pagelconColor: '#333',
                        pageTextStyle: {
                            color: '#666'// 页码文字颜色
                        },
                        // data: arr
                    },
                    series: data.series.map((item, index) => {
                        if (!this.detailDialogNameList.includes(item.name)) this.detailDialogNameList.push(item.name)
                        return {
                            name: item.name,
                            data: item.data,
                            itemStyle: {
                                normal: {
                                    label: {
                                        show: true, // 显示拐点数据
                                        color: this.colorList[index]
                                    },
                                    color: this.colorList[index]
                                },
                            },
                        }
                    }),
                    yAxis: [
                        {
                            type: "value",
                            unit: "元"
                        }
                    ]
                }
            }).catch(error => {
                console.error(`获取数据失败: ${error}`);
            });
        },
        handleDialogClose() {
            this.dialogVisible = false
            this.dialogLineChartData = {}
        },
        // 图表月周日点击逻辑
        LeftChange(event, type, index) {
            const { day, enumObj, lookSaveType } = this
            const { title, selectedStep } = event
            // 移除旧数据
            if (lookSaveType) {
                if (type === 'line') {
                    this.clearChartData(this.SaveLeftCharts[0])
                } else {
                    this.clearChartData(this.SaveLeftCharts[1])
                }
            } else {
                if (type === 'left') {
                    this.clearChartData(this.leftCharts[index])
                } else {
                    this.clearChartData(this.rightCharts[index])
                }
            }
            this.lookSaveType ? this.lookSave({ label: "库存金额" }, true, undefined, day[selectedStep]) : this.getData(enumObj[title], day[selectedStep])
        },
        // 移除旧数据公共方法
        clearChartData(chart) {
            chart.data.xAxis = [];
            chart.data.series = []
        },
        // 清除所有数据
        clearAllCharts() {
            for (let i = 0; i < this.leftCharts.length; i++) {
                this.clearChartData(this.leftCharts[i]);
            }
            for (let j = 0; j < this.rightCharts.length; j++) {
                this.clearChartData(this.rightCharts[j]);
            }
            for (let k = 0; k < this.SaveLeftCharts.length; k++) {
                this.clearChartData(this.SaveLeftCharts[k]);
            }
        },
        // 组织展开选择需要展示的数据
        showSelect(event) {
            const { copyRegionVos, clickDown } = this
            this.elLoading = true
            // this.setLoading()
            if (!clickDown) {
                getRegion('getRegionShowAll', this.selectedAll ? this.selectedAll : '全部', this.SN, this.organizationSelect).then(showAllRes => {
                    const { regionShowVos, headerVo, customerScaleVos } = showAllRes.data;
                    this.upRegionMapData(copyRegionVos, regionShowVos, headerVo, customerScaleVos)
                }).catch(err => {
                    this.elLoading = false
                })
            } else {
                this.getOffData()
            }
        },
        // 鼠标滑动显示弹窗
        showPopover(index, item) {
            this.hoveredIndex = index
            const parentRect = this.$refs.parent.getBoundingClientRect();
            const childRect = this.$refs.child[index].getBoundingClientRect();
            // 判断子元素相对于父元素的位置
            const isAtLeftEdge = childRect.left <= parentRect.left;
            const isAtRightEdge = childRect.right >= parentRect.right - 250;
            const isAtBottomEdge = childRect.bottom >= parentRect.bottom - 100;
            const isAtTopEdge = childRect.top === parentRect.top;
            // 设置默认位置值
            this.leftValue = -50;
            this.TopValue = 50;
            // console.log(isAtRightEdge, isAtBottomEdge,childRect.right, parentRect.right - 250);
            if (isAtLeftEdge) {
                this.leftValue = 0;
                this.TopValue = isAtBottomEdge ? -100 : 50; // 左边缘时高度
            } else if (isAtTopEdge && isAtRightEdge) {
                this.leftValue = -200; // 左上角时
            } else if (isAtBottomEdge) {
                this.TopValue = -100; // 底边缘
                this.leftValue = isAtRightEdge ? -250 : -50; // 底边缘时判断左右
            } else if (isAtRightEdge) {
                this.leftValue = -250; // 右边缘
                this.TopValue = isAtBottomEdge ? -150 : -120; // 右边缘时高度
            }

        },
        // 移出选中盒子
        hidePopover() {
            this.hoveredIndex = null;
            // if (this.clickDown) this.updataTabBottomData(this.copyChickCityBottomData)
        },
        // 组织与行政区选择
        selectedAreaChange(event) {
            const { FullYear, copyCustomerScaleVos, copyHeaderVo } = this
            this.reset()
            this.clearAllCharts()
            if (event === '组织') {
                this.elLoading = true
                this.newOrgType = 'area'
                this.SN = 'SN'
                this.newOrgName = undefined
                this.organizationRadio = '省内'
                if (!this.lookSaveType) {
                    this.cityName = '中国'
                    this.cityLevel = ''
                    this.clickDown = false
                    this.regionName = undefined
                    this.markerObj = undefined
                    this.getRegionData()
                    this.fetchAllData()
                } else {
                    this.cityLevel = ''
                    this.cityName = ''
                    this.getRegionData()
                    this.lookSave({ label: '库存金额' }, true)
                }
            } else {
                this.newOrgType = ''
                this.cityLevel = 'country'
                this.clickDown = false
                this.SN = 'SN'
                this.organizationRadio = '省内'
                if (!this.lookSaveType) {
                    this.newOrgType = ''
                    this.cityName = '中国'
                    this.clickDown = false
                    this.newOrgType = undefined
                    this.regionName = undefined
                    this.newOrgName = undefined
                    this.cityLevel = 'country'
                    this.markerObj = undefined
                    this.fetchAllData()
                    this.getTabTopData()
                    this.getTabBottomData()
                } else {
                    this.cityName = ''
                    this.lookSave({ label: '库存金额' }, true)
                }
            }
        },
        // 返回上一级
        async gotoBack() {
            this.clickDown = false
            // const { copyRegionVos, copyRegionShowVos, copyHeaderVo, copyCustomerScaleVos } = this
            // this.upRegionMapData(copyRegionVos, copyRegionShowVos, copyHeaderVo, copyCustomerScaleVos)
            this.newOrgType = undefined
            this.newOrgName = undefined
            this.elLoading = true
            this.markerObj = undefined
            this.clearAllCharts()
            this.reset()
            this.newOrgType = 'area'
            await this.getRegionData()
            if (!this.lookSaveType) {
                await this.fetchAllData()
            } else {
                this.cityName = ''
                this.cityLevel = ''
                this.lookSave({ label: '库存金额' }, true)
            }
        },
        gotoCity(val) {
            if (this.clickDown) {
                // 点击不重复的办事处才请求ajax
                if (this.newOrgName != val.name) {
                    getRegion("getCustomerScale", this.selectedAll || '全部', this.SN, this.organizationSelect, val.regionName, val.officeName).then(res => {
                        const { customerScaleVos } = res.data
                        this.reset()
                        this.clearAllCharts()
                        this.newOrgType = 'office'
                        this.newOrgName = val.name
                        this.lookSaveType ? this.lookSave({ label: '库存金额' }, true) : this.fetchAllData()
                        this.updataTabBottomData(customerScaleVos)
                        getRegion('getOfficeShowAll', this.selectedAll ? this.selectedAll : "全部", this.SN, this.organizationSelect, val.regionName, val.officeName)
                            .then(showAllRes => {
                                const { regionShowVos } = showAllRes.data
                                const matchedShowVo = regionShowVos.find(nowItem => nowItem.officeName === val.officeName);
                                this.updataTabTopData(matchedShowVo)
                            })
                    }).catch(err => {
                        console.error(`获取数据失败: ${err}`);
                    })
                }
            }
            if (val.offices) {
                this.clearAllCharts()
                this.elLoading = true
                this.clickDown = true
                this.organizationContent = undefined
                this.newOrgName = this.regionName = val.regionName
                this.newOrgType = "area"
                this.hoveredIndex = null
                this.reset()
                this.getOffData(val.regionName)
                if (!this.lookSaveType) {
                    this.fetchAllData()
                } else {
                    this.cityName = ''
                    this.cityLevel = ''
                    this.newOrgType = 'area'
                    this.lookSave({ label: '库存金额' }, true)
                }
            }
        },

        getOffData() {
            // this.setLoading()
            getRegion('getOfficeShowAll', this.selectedAll ? this.selectedAll : "全部", this.SN, this.organizationSelect, this.regionName).then(res => {
                console.log(res, "getOfficeShowAll");
                const { customerScaleVos, headerVo, regionShowVos } = res.data
                this.copyChickCityBottomData = JSON.parse(JSON.stringify(customerScaleVos))
                this.copyChickCityTopData = JSON.parse(JSON.stringify(headerVo))
                this.organizationContent = this.upOrganizationArrayData(customerScaleVos, headerVo, regionShowVos, 'officeName')
            }).catch(err => {
                this.elLoading = false
            })
        },
        setLoading() {
            this.elLoading && this.elLoading.close()
            this.elLoading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        },
        getRegionData(url, regionName) {
            // this.setLoading()
            getRegion(url, this.selectedAll ? this.selectedAll : "全部", this.SN, this.organizationSelect, regionName).then(res => {
                const { regionVos } = res.data;
                console.log(res, '---res');
                // 获取展示所有数据
                return getRegion('getRegionShowAll', this.selectedAll ? this.selectedAll : "全部", this.SN, this.organizationSelect)
                    .then(showAllRes => {
                        const { regionShowVos, headerVo, customerScaleVos } = showAllRes.data;
                        this.copyRegionVos = JSON.parse(JSON.stringify(regionVos))
                        this.copyRegionShowVos = JSON.parse(JSON.stringify(regionShowVos))
                        this.copyHeaderVo = JSON.parse(JSON.stringify(headerVo))
                        this.copyCustomerScaleVos = JSON.parse(JSON.stringify(customerScaleVos))
                        this.upRegionMapData(regionVos, regionShowVos, headerVo, customerScaleVos)
                    }).catch(
                    // this.elLoading = false
                )
            }).catch(error => {
                console.error('接口出错>>>>>', error);
            });
        },
        upRegionMapData(data, _data, _headerData, _bottomData) {
            const colorWeight = {
                '红色': 1,
                '黄色': 2,
                '绿色': 3
            };
            this.redColorArr = []
            this.yellowColorArr = []
            this.greenColorArr = []
            const organizationSelectMap = {
                '销售目标': 'contractAmt',
                '销售完成': 'salesAmt',
                '经销商出货': 'outboundAmt',
                '终端进货': 'terminalSignAmt',
                '费用投入': 'costAmt',
                '开瓶扫码': 'openCnt',
                '异地扫码': 'notNormalOpenCnt'
            };
            const selectedKey = organizationSelectMap[this.organizationSelect];
            const nowData = data.map(item => {
                const matchedShowVo = _data.find(nowItem => nowItem.regionName === item.regionName);
                if (matchedShowVo) {
                    if (matchedShowVo.color === '红色') this.redColorArr.push(matchedShowVo[selectedKey])
                    if (matchedShowVo.color === '黄色') this.yellowColorArr.push(matchedShowVo[selectedKey])
                    if (matchedShowVo.color === '绿色') this.greenColorArr.push(matchedShowVo[selectedKey])
                    return {
                        ...item,
                        up: matchedShowVo.rankChange > 0,
                        rise: Math.abs(matchedShowVo.rankChange),
                        name: item.regionName,
                        color: matchedShowVo.color ?? '绿色',
                        number: matchedShowVo[selectedKey],
                        amount: this.createAmountData(matchedShowVo)
                    };
                }
            }).filter(item => item !== undefined);
            nowData.sort((a, b) => {
                const colorComparison = colorWeight[a.color] - colorWeight[b.color];
                if (colorComparison !== 0) {
                    return colorComparison;
                }
                return b.number - a.number;
            });
            this.elLoading = false
            this.organizationContent = nowData
            this.updataTabTopData(_headerData)
            this.updataTabBottomData(_bottomData)
        },
        // 地图点击
        handleMapClick(clickedArea) {
            console.log("点击了那个地区", clickedArea, this.lookSaveType);
            this.clearAllCharts()
            this.cityName = clickedArea.name
            this.cityLevel = clickedArea.level
            if (JSON.stringify(this.markerObj) != {}) this.markerObj = undefined
            this.lookSaveType ? this.lookSave({ label: '库存金额' }, true) : this.fetchAllData()
            // this.getRegionMapDataAjax('getRegionMapData', this.FullYear, clickedArea.level, clickedArea.name)
            this.getTabTopData()
            this.getTabBottomData()
            this.reset()
        },
        handleBack() {
            this.markerObj = undefined
        },
        // 矩阵省内省外选择
        organizationRadioChange(event) {
            const SN = {
                省内: "SN",
                省外: "SW"
            }
            this.reset()
            this.SN = SN[event]
            this.elLoading = true
            this.clickDown = false
            this.newOrgName = undefined
            this.newOrgType = "area"
            if (!this.lookSaveType) {
                this.clearAllCharts()
                this.fetchAllData()
            } else {
                this.cityName = ''
                this.cityLevel = ''
                this.newOrgType = 'area'
                this.lookSave({ label: '库存金额' }, true)
            }

            // if (!clickDown) 
            this.getRegionData()
            // else this.getOffData()
        },
        // 选择品牌
        selectedAllChange(event) {
            const { clickDown, selectedArea, lookSaveType } = this
            this.clearAllCharts()
            this.selectedAll = event
            this.reset()
            if (selectedArea === '组织') {
                this.elLoading = true
                if (lookSaveType) {
                    this.lookSave({ label: '库存金额' }, true)
                } else {
                    this.fetchAllData()
                }
                if (!clickDown) this.getRegionData()
                else this.getOffData()
            } else {
                this.fetchAllData()
                this.getTabBottomData()
                this.getTabTopData()
            }

        },
        createAmountData(item) {
            const amountObj = {
                'contractAmt': '销售目标金额',
                'salesAmt': '销售完成金额',
                'outboundAmt': '经销商出货金额',
                'terminalSignAmt': '终端进货金额',
                'costAmt': '费用投入金额',
                'openCnt': '开瓶扫码瓶数',
                'notNormalOpenCnt': '异地扫码瓶数'
            };
            return Object.keys(amountObj).map(key => ({
                name: amountObj[key],
                money: `${this.setYuanUnit(item[key])[0]}${this.setYuanUnit(item[key], amountObj[key].includes("瓶"))[1]}`,
                Odata: item[key]
            }));
        },
        // 地图mark点击
        async markerClick(event) {
            // getRegionMapDataByCustomer
            console.log(event, '---markerClick');
            const res = await getRegionMap('getRegionMapDataByCustomer', '', '', '', '', '', '', '', event.data.mainCustomerCode)
            this.markerObj = res.data
            if (res.success) {
                this.reset()
                this.clearAllCharts()
                this.lookSaveType ? this.lookSave({ label: '库存金额' }, true) : this.fetchAllData()
                // this.fetchAllData()
                this.updataTabTopData(res.data)
            }
        },
        //  查看库存
        lookSave(item, type, dateStr, day = 'month', brandType, mainCustomerCode, dateList, monthWeek) {
            if (item.label.includes('库存金额')) {
                this.clearAllCharts()
                this.lookSaveType = type ?? !this.lookSaveType
                if (this.selectedArea === '组织') {
                    this.cityLevel = ''
                    // this.newOrgType =  'area'
                    this.cityName = ''
                    // if(!this.lookSaveType) {
                    //     this.cityName = '中国'
                    //     this.cityLevel = 'country'
                    //     this.newOrgType = undefined
                    // }
                }
                if (this.lookSaveType || type) {
                    const requests = [
                        'getCustomerPurchaseSalesLineChartData',
                        'getRegionInventorySalesBarChartData'
                    ]

                    // url = 'getSalesLineChartData', dateType = 'month', dateStr, brandType, mainCustomerCode, dateList, monthWeek
                    Promise.allSettled(requests.map(url => this.getData(url, day, dateStr, url === 'getRegionInventorySalesBarChartData' ? this.brandType : '', mainCustomerCode, dateList, monthWeek))).then(res => {
                        console.log("所有接口获取成功");
                    })
                }
                if (!type && !this.lookSaveType) {
                    this.reset()
                    this.fetchAllData()
                }
                // this.getData('getCustomerPurchaseSalesLineChartData')
            } else {
                Message({
                    message: "功能开发中，敬请期待",
                    // type: 'error',
                    duration: 1 * 1000
                })
            }
        },
        dataZoom(event) {
            const { day, enumObj } = this
            const { data, title, day: selectedStep } = event
            if (data) this.getData(enumObj[title], day[selectedStep], data)
        },
        reset() {
            const chartsArrays = [this.leftCharts, this.rightCharts, this.SaveLeftCharts];
            chartsArrays.forEach(charts => {
                charts.forEach(item => {
                    console.log(item);
                    this.$set(item, 'day', '月')
                })
            })
        },
        areAllSeriesDataPresent(...chartsArrays) {
            const checkSeriesData = (data) => {
                return data.every(item => {
                    return item.data && Array.isArray(item.data.series) && item.data.series.length > 0
                })
            }
            return chartsArrays.every(checkSeriesData)
        }
    },
    watch: {
        isBrowserFullScreen(newVal) {
            if (newVal) {
                console.log(newVal, '---newVal');
                // this.resize = newVal;
            }
        }
    }
}

</script>

<style lang="scss" scoped>
.FnSetBgc {
    background: #F84A49 !important;
}

.FnSetColor {
    color: #fff !important;
}

.operation-map {
    height: 100vh;
    background: #f5f5f5;
    display: flex;
    flex-direction: column;

    .header {
        height: 110px;
        background: #e4393c;
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        position: relative;
        background: url('../../assets/BI/header_bg.png') no-repeat center center;
        background-size: 100% 100%;

        // &::after {
        //     content: '';
        //     position: absolute;
        //     bottom: 0;
        //     left: 0;
        //     right: 0;
        //     height: 4px;
        //     background: linear-gradient(90deg, #ffeb3b, #ffc107);
        // }


        .time {
            font-size: 17px;
            color: rgba(255, 255, 255, 0.9);
            width: 250px !important;
            display: block;
            margin-bottom: 50px;
        }

        .title {
            font-weight: 600;
            font-size: 36px;
            margin-bottom: 25px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
            width: 250px;
            margin-bottom: 50px;

            .button-group {
                display: flex;
                align-items: center;
                gap: 10px;

                ::v-deep .el-select--small>.el-input>.el-input__inner {
                    width: 65px !important;
                    text-align: center !important;
                }

                :deep(.el-radio-group) {
                    .el-radio-button__inner {
                        background: rgba(255, 255, 255, 0.1);
                        border: 1px solid rgba(255, 255, 255, 0.2);
                        color: white;
                        height: 32px;
                        line-height: 32px;
                        padding: 0 15px;

                        &:hover {
                            background: rgba(255, 255, 255, 0.2);
                        }
                    }

                    .el-radio-button__original-radio:checked+.el-radio-button__inner {
                        background: white;
                        color: #e4393c;
                        border-color: white;
                        box-shadow: none;
                    }
                }

                .all-select {
                    width: 100px;

                    :deep(.el-input__inner) {
                        // background: rgba(255, 255, 255, 0.1);
                        // border: 1px solid rgba(255, 255, 255, 0.2);
                        // color: white;
                        // height: 32px;

                        &::placeholder {
                            color: rgba(255, 255, 255, 0.8);
                        }
                    }

                    :deep(.el-select__caret) {
                        color: white;
                    }
                }
            }
        }
    }

    .content {
        flex: 1;
        position: relative;
        overflow: auto;
        background: #fff;

        .charts-container {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            z-index: 3;
            display: flex;
            justify-content: space-between;
            padding: 20px;
            pointer-events: none;

            .left-charts,
            .right-charts {
                width: 25vw;
                display: flex;
                flex-direction: column;
                gap: 20px;
                pointer-events: auto;

                .chart-item {
                    background: white;
                    border-radius: 4px;
                    // height: calc(100vh - 673px);
                    height: calc((100vh / 3) - 60px);
                    box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.08);
                    cursor: pointer;
                    transition: all 0.3s;
                    border-radius: 15px;

                    &:hover {
                        transform: translateY(-5px);
                        box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
                    }
                }
            }
        }

        .map-container {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            height: calc(100vh - 130px);
            background: #FCF7F7;
        }
    }
}

.map-overview {
    position: relative;
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 40px;
    z-index: 2;
    left: 50%;
    margin-left: -25%;
    padding: 20px 48px 0;
    background: transparent;

    // background: #000;
    .overview-item {
        text-align: center;
        border-radius: 10px;
        border: 1px solid #FFADAD;
        box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.08);
        // white-space: nowrap;
        cursor: pointer;
        background: #fff;
        // min-width: 120px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .value-container {
            margin-bottom: 5px;
            font-weight: bold;
            color: #EA1111;
            white-space: nowrap;

            .value {
                font-size: calc(0.1em + 1.6vw);
            }

            .unit {
                font-size: calc(0.02em + 1vw);
                ;
                margin-left: 4px;

            }

            .percent {
                font-size: calc(0.1em + 1.6vw);
                margin-left: 4px;

            }
        }

        .label {
            white-space: nowrap;
            font-size: calc(0.02em + 0.8vw);
            ;
            color: #333;
        }
    }
}

:deep(.el-dialog__wrapper) {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    margin: 0;
    z-index: 2000;
}

:deep(.chart-detail-dialog) {
    .el-dialog {
        margin-top: 8vh !important;
    }
}

.organization {
    position: relative;
    width: 50%;
    display: flex;
    justify-content: center;
    // align-items: center;
    flex-direction: column;
    left: 50%;
    margin-left: -25%;
    padding: 20px 48px;

    &_title {
        display: flex;
        align-items: center;
        width: 100%;
        justify-content: space-between;

        &_radio {
            border: 1px solid #FFADAD;
            box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.08);
            border-radius: 6px
        }

        &_right {
            display: flex;
            align-items: center;
            column-gap: 18px;

            &_back {
                cursor: pointer;
                width: 144px;
                height: 37px;
                text-align: center;
                border-radius: 6px;
                border: 1px solid #999;
                display: flex;
                justify-content: center;
                align-items: center;
                column-gap: 10px;
            }

            &_back>div {
                color: #333;
                font-size: 16px;
            }

            &_all {
                ::v-deep .el-input {
                    font-size: 18px;
                    align-items: center;
                }

                ::v-deep .el-input__inner {
                    width: 105px !important;
                    height: 35px !important;
                    text-align: center !important;
                }

                ::v-deep .el-input__inner,
                ::v-deep .el-select__caret {
                    color: #000 !important;
                }

                ::v-deep .el-icon-arrow-up:before {
                    content: "\e790";
                }

                &_Select {
                    display: flex;
                    column-gap: 12px;
                    box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.17);
                    border: 1px solid #FFADAD;
                    border-radius: 6px;
                    // width: 144px;
                    padding: 10px 20px;
                    height: 37px;
                    text-align: center;
                    justify-content: center;
                    align-items: center;

                }
            }
        }
    }

    &_content {
        display: flex;
        flex-wrap: wrap;
        // align-items: center;
        margin-top: 26px;
        column-gap: 20px;
        row-gap: 30px;
        cursor: pointer;
        max-height: calc(100vh - 590px);
        overflow-y: auto;
        min-height: 300px;

        &_item {
            background: #333;
            color: #fff;
            font-size: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            border-radius: 6px;
            position: relative;
            padding: 0 10px;

            //   text-align: center;
            &_top {
                display: flex;
                align-items: center;
                column-gap: 5px;

                &_right {
                    display: flex;
                    font-size: 13px;
                }
            }
        }
    }

    /* 修改滚动条整体样式 */
    &_content::-webkit-scrollbar {
        width: 6px;
        /* 竖条宽度 */
        height: 6px;
        /* 横条高度 */
    }

    /* 滚动条轨道（背景） */
    &_content::-webkit-scrollbar-track {
        background: transparent;
        /* 透明背景 */
    }

    /* 滚动条滑块 */
    &_content::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        /* 半透明灰色 */
        border-radius: 3px;
        /* 圆角 */
    }

    /* 鼠标悬停时滑块颜色 */
    &_content::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, 0.3);
    }

    &_bottom {
        margin-top: 20px;
        position: fixed;
        bottom: 150px;

        &_title {
            color: #3F1E25;
            font-size: 12px;
        }

        &_item {
            margin-top: 9px;
            display: flex;
            align-items: center;
            column-gap: 6px;
            row-gap: 5px;
        }

        &_item>div {
            font-size: 10px;
            color: #333;
        }
    }

    ::v-deep .el-radio-button__inner {
        padding: 8px 32px !important;
        border: none !important;
        border-radius: 6px;
        margin: 3px;

    }

}

.tableData {
    position: fixed;
    bottom: 10px;
    width: 46%;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 40px;
    z-index: 2;
    left: 50%;
    margin-left: -23%;
    padding: 10px 12px;
    border: 1px solid #FFADAD;
    border-radius: 10px;
    box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.08);
    background: #fff;

    ::v-deep .el-table {
        border-radius: 10px;
    }

    ::v-deep .el-table__body-wrapper {
        overflow: hidden;
    }
}

.table-cell {
    display: flex;
    justify-content: center;
    align-items: center;
}

.amount-cell {
    display: flex;
    justify-content: center;
    align-items: center;

    &_right {
        display: flex;
        font-size: 11px;
    }
}

.el-select {

    box-shadow: 0px 0px 20px 0px rgba(177, 0, 0, 0.08);
    border-radius: 6px;
}

.map-wrapper {
    flex: 1;
    width: 100%;
    min-height: 500px;
    height: calc(100vh - 250px);
    background: #fff;
    border-radius: 4px;
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    position: relative;
}

.hovered {
    position: absolute;
    width: 258px;
    background: rgba(136, 119, 9, 0.78);
    top: 70px;
    z-index: 9999999;
    left: -50px;
    border: 1px solid #FFE24D;
    backdrop-filter: blur(6px);
    box-shadow: 0px 5px 25px 0px rgba(51, 51, 51, 0.18);
    border-radius: 10px;
    text-align: center;

    // overflow-y: auto;
    &_title {
        font-size: 18px;
        margin-top: 14px;
    }

    &_item {
        font-size: 13px;
        padding: 11px 12px 22px 12px;

        &_for {
            display: flex;
            margin-bottom: 6px;
            align-items: center;
            justify-content: space-between;
        }
    }
}

.iconBox {
    width: 40px;
    height: 101px;
    border: 1px solid #ffadad;
    border-radius: 6px;
    position: fixed;
    bottom: 130px;
    left: 71%;
    z-index: 9;
    background: #fff;
    font-size: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    row-gap: 16px;
}

.mark_tab {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 10px;
    justify-content: space-between;

    &_left {
        display: flex;
        align-items: center;
        column-gap: 24px;
    }

    &_right {
        display: flex;
        column-gap: 10px;

        &_details {
            &_top {
                font-size: 14px;
                color: #333;
                display: flex;
                column-gap: 10px;
                margin-bottom: 8px;
            }

            &_text {
                display: flex;
                flex-direction: column;
                font-size: 14px;
                row-gap: 6px;
            }
        }
    }
}

.warningList {
    display: flex;
    border: 1px solid #C44A4D;
    border-radius: 4px;
    color: #C44A4D;
    font-size: 12px;
    align-items: center;
}
</style>
